package com.whfc.base.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.base.dao.AppFileExportMapper;
import com.whfc.base.dto.AppExportDTO;
import com.whfc.base.entity.AppFileExport;
import com.whfc.base.param.AppFileExportParam;
import com.whfc.base.service.AppExportService;
import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.result.PageData;
import com.whfc.common.util.PageUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 导出记录
 * @Author hw
 * @Date 2021-07-22 10:11
 * @Version 1.0
 */
@DubboService(interfaceClass = AppExportService.class, version = "1.0.0")
public class AppExportServiceImpl implements AppExportService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppFileExportMapper appFileExportMapper;

    @Autowired
    private FileHandler fileHandler;

    @Override
    public PageData<AppExportDTO> list(Integer deptId, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("导出记录列表，deptId：{}，pageNum：{}，pageSize：{}", deptId, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<AppExportDTO> list = appFileExportMapper.selectByDeptId(deptId);
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public Integer install(AppFileExportParam param) throws BizException {
        logger.info("保存导出记录，param：{}", param);
        AppFileExport fileExport = new AppFileExport();
        BeanUtils.copyProperties(param, fileExport);
        appFileExportMapper.insertSelective(fileExport);
        return fileExport.getId();
    }

    @Override
    public void update(AppFileExportParam param) throws BizException {
        logger.info("更新导出记录，param：{}", param);
        AppFileExport fileExport = new AppFileExport();
        BeanUtils.copyProperties(param, fileExport);
        appFileExportMapper.updateByPrimaryKeySelective(fileExport);
    }

    @Override
    public void updateFailureState() throws BizException {
        appFileExportMapper.updateFailureState();
    }

    @Override
    public void delOverdueFile() throws BizException {
        List<AppFileExport> appFileExports = appFileExportMapper.selectByOverdue();
        if (appFileExports.isEmpty()) {
            return;
        }
        List<String> urls = appFileExports.stream().map(AppFileExport::getFileUrl).collect(Collectors.toList());
        fileHandler.delete(urls);
    }
}
